/*
 * ServidorJTurboNote.java
 *
 * Created on 02/07/2007, 10:46:21
 *
 */
package br.com.grillo.jturbonote;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import org.apache.commons.io.IOUtils;
import static br.com.grillo.jturbonote.Main.logger;
import static br.com.grillo.jturbonote.Configuracao.*;

/**
 *
 * @author grillo
 */
public class ServidorJTurboNote {

    public static ListenerJTurboNote listener;
    public static int[] PORTO_PADRAO = {39681};
    //	static int[] PORTO_PADRAO = {39682};

    public void init() throws IOException {
        listener = new ListenerJTurboNoteImpl();
        String portos = getValor("portos-servidor");
        if (portos == null) {
            for (int porto : PORTO_PADRAO) {
                new ThreadServidor(porto, listener).start();
            }
        } else {
            for (String porto : portos.split(",")) {
                new ThreadServidor(Integer.parseInt(porto), listener);
            }
        }
    }
}

class ThreadServidor extends Thread {

    private int porto;
    boolean ativado;
    private ListenerJTurboNote listener;

    ThreadServidor(int porto, ListenerJTurboNote listener) {
        super("JTurboNote [" + porto + "]");
        this.porto = porto;
        this.listener = listener;
    }

    @Override
    public void run() {
        try {
            final ServerSocket server = new ServerSocket(porto);
            ativado = true;
            Socket client;
            while (ativado) {
                try {
                    client = server.accept();
                    listener.onNewNote(client.getInetAddress(), IOUtils.toByteArray(client.getInputStream()));
                    client.close();
                } catch (IOException ioEx) {
                    logger.log(Level.SEVERE, "Erro ao receber nota", ioEx);
                }
            }
        } catch (IOException ioEx) {
            logger.log(Level.SEVERE, "Erro ao criar servidor", ioEx);
        }
    }
}
